package com.heima.task.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UUID;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-02 14:45
 */
@RestController
public class TestController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/test")
    public void test() {
//        String lockkey = "lock107-test";
        String key = "stock";
//
//        String s1 = UUID.randomUUID().toString();
//        while (!Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(lockkey, s1, Duration.ofSeconds(30)))) {
//            try {
//                Thread.sleep(50L);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//
//        try {
//            String s = stringRedisTemplate.opsForValue().get(key);
//            Long stock = Long.valueOf(s);
//            stock -= 1;
//            if (stock < 0) {
//                return;
//            }
//            //扣减库存
//            stringRedisTemplate.opsForValue().set("stock", stock.toString());
//        } finally {
//            if(s1.equals(stringRedisTemplate.opsForValue().get(lockkey))){
//                stringRedisTemplate.delete(lockkey);
//            }
//        }

        RLock lock = redissonClient.getLock("lock107-test2");
        lock.lock();
        try{
            String s = stringRedisTemplate.opsForValue().get(key);
            Long stock = Long.valueOf(s);
            stock -= 1;
            if (stock < 0) {
                return;
            }
            //扣减库存
            stringRedisTemplate.opsForValue().set("stock", stock.toString());
        }finally {
            //判断是否我加的锁
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }


    }
}
